package com.cf.user.login.service;

import com.cf.user.core.EnumSessionCode;
import com.cf.user.login.model.UserInfo;
import com.cf.util.NumberUtil;
import com.cf.util.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * game-server-TokenManager
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/5/28 下午 03:26
 */
@Slf4j
public class DefaultTokenManagerImpl implements TokenManager {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserInfoService userInfoService;

    public String setToken(UserInfo userInfo, HttpServletRequest request, HttpServletResponse response) {
        String token = registerToken(userInfo);
        setToken(token, response);
        return token;
    }

    /**
     * 注册一个token
     *
     * @param userInfo
     * @return
     */
    public String registerToken(UserInfo userInfo) {
        long userId = userInfo.getId();
        return registerToken(userId);
    }

    public String registerToken(long userId) {
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(EnumSessionCode.SESSION_PREFIX.getValue() + token, String.valueOf(userId));
        redisTemplate.expire(EnumSessionCode.SESSION_PREFIX.getValue() + token, 3600 * 12, TimeUnit.SECONDS);
        return token;
    }


    private void setToken(String token, HttpServletResponse response) {
        RequestUtil.addCookie(response, EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue(), token, 3600 * 5);
    }

    @Override
    public UserInfo userInfo(HttpServletRequest request) {
        return userInfo(getToken(request));
    }


    /**
     * 获取信息的同时刷新token的有效期
     *
     * @param token
     * @return
     */
    public UserInfo userInfo(String token) {
        String s = redisTemplate.opsForValue().get(EnumSessionCode.SESSION_PREFIX.getValue() + token);
        redisTemplate.expire(EnumSessionCode.SESSION_PREFIX.getValue() + token, 3600 * 12, TimeUnit.SECONDS);
        if (NumberUtil.isDigit(s)) {
            return userInfoService.getUserInfo(s);
        }
        return null;
    }

    /**
     * 获取token
     *
     * @param request
     * @return
     */
    public String getToken(HttpServletRequest request) {
        String cookie = RequestUtil.getCookie(request, EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue());
        if (cookie == null) {
            cookie = request.getParameter(EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue());
        }
        if (cookie == null) {
            cookie = request.getHeader(EnumSessionCode.SESSION_TOKEN_CLIENT_KEY.getValue());
        }
        return cookie;
    }

}
